import express from 'express';
import { createServer } from 'https';
import cors from 'cors';
import { Server } from 'socket.io';
import fs from 'fs';

// 创建Express应用
const app = express();
app.use(cors());

// 证书配置部分
const httpsOptions = {
    key: fs.readFileSync('../public/cert/localhost-key.pem'),
    cert: fs.readFileSync('../public/cert/localhost.pem')
};

// 创建HTTPS服务器
const httpsServer = createServer(httpsOptions, app);

// 定义一个简单的路由
app.get('/', (req, res) => {
    res.send('Hello World!');
});

// 创建Socket.io服务器并关联到HTTPS服务器
const io = new Server(httpsServer, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
});

// 当有新客户端连接时的处理逻辑
io.on("connection", (socket) => {
    console.log("New client connected");

    // 进入房间
    socket.on("joinRoom", (payload) => {
        const { roomId, userId } = payload;
        socket.join(roomId);
        socket.join(userId);

        socket.to(roomId).emit("message", {
            type: "joinRoom",
            data: {
                ...payload,
                roomCount: io.sockets.adapter.rooms.get(roomId)?.size
            }
        });
        console.log("当前房间人数", io.sockets.adapter.rooms.get(roomId)?.size)
    })

    socket.on("offer", (payload) => {
        const { newUserId } = payload;
        socket.to(newUserId).emit("message", {
            type: "offer",
            data: payload
        });
    })

    socket.on("answer", (payload) => {
        const { fromUserId } = payload;
        socket.to(fromUserId).emit("message", {
            type: "answer",
            data: payload
        });
    })

    socket.on("candidate", (payload) => {
        const { fromUserId } = payload;
        socket.to(fromUserId).emit("message", {
            type: "candidate",
            data: payload
        });
    })
});

// 启动HTTPS服务器，监听指定端口（这里假设是3000，你可根据需要修改）
httpsServer.listen(3000, () => {
    console.log("Server is running on port 3000");
});